﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ECommerce.BLL.Product;
using ECommerce.Model.Product;
using ECommerce.BLL.Member;
using ECommerce.Model.Member;
using ECommerce.Common;
using Jzy.Core.Utility;

namespace ECommerce.Web.Site
{
    public partial class Shopping1 : System.Web.UI.Page
    {      

        private ECProductBO Product
        {
            get
            {
                return ECProductBO.Instance<ECProductBO>();
            }
        }

     

        protected void Page_Load(object sender, EventArgs e)
        {

            if (!IsPostBack)
            {                
                BindView();
            }
        }

        private void BindView()
        {
            string shoppingCart = "";
            if (Request.Cookies["ShoppingCart"] != null)
            {
                shoppingCart = Request.Cookies["ShoppingCart"].Value;
            }

            
            string[] idCounts = shoppingCart.Split(',');
               

            List<ECProductInfo> tmpInfos = new List<ECProductInfo>();
            foreach (string idcount in idCounts)
            {
                if (idcount != "")
                {
                    ECProductInfo info = new ECProductInfo();
                    info.ID = int.Parse(idcount.Split('_')[0]);
                    info.BuyCount = int.Parse(idcount.Split('_')[1]);
                    info.Size = Server.UrlDecode(idcount.Split('_')[2]);
                    tmpInfos.Add(info);
                }
            }

            List<ECProductInfo> list = this.Product.GetList(tmpInfos.Select(T=>T.ID));

            double totalPrice = 0;
            int productCount = 0;
            foreach (ECProductInfo info in list)
            {
                ECProductInfo tmpInfo = tmpInfos.Where(T=>T.ID == info.ID).First();
                info.BuyCount = tmpInfo.BuyCount;

                info.Size = tmpInfo.Size;

                totalPrice += (info.CurrentPrice * info.BuyCount);
                productCount += info.BuyCount;
            }

            rpt.DataSource = list;
            rpt.DataBind();

            litProductCount.Text = productCount.ToString();
            litTotalPrice.Text = totalPrice.ToString("c2");
            
        }

        

        protected void rpt_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "Delete")
            {
                string shoppingCart = "";
                foreach (RepeaterItem item in rpt.Items)
                {
                    if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
                    {
                        Literal litID = item.FindControl("litID") as Literal;
                        Literal litSize = item.FindControl("litSize") as Literal;
                        TextBox txtBuyCount = item.FindControl("txtBuyCount") as TextBox;

                        shoppingCart += litID.Text + "_" + txtBuyCount.Text + "_" + Server.UrlEncode(litSize.Text) + ",";

                    }
                }
                shoppingCart = shoppingCart.TrimEnd(',');



                string productID = e.CommandArgument.ToString();
                string[] tmp = shoppingCart.Split(',');
                shoppingCart = "";
                foreach (string str in tmp)
                {
                    if (!str.StartsWith(productID + "_"))
                    {
                        shoppingCart += str + ",";
                    }
                }
                shoppingCart = shoppingCart.TrimEnd(',');

                HttpCookie cookie = new HttpCookie("ShoppingCart", shoppingCart);
                cookie.Expires = DateTime.Now.AddHours(12);
                Response.Cookies.Add(cookie);

                Response.Redirect("Shopping1.aspx");
            }
            else if (e.CommandName == "Decrease")
            {
                double currentPrice = double.Parse(e.CommandArgument.ToString());
                TextBox txtBuyCount = e.Item.FindControl("txtBuyCount") as TextBox;
                int count = int.Parse(txtBuyCount.Text);
                if (count > 1)
                {
                    txtBuyCount.Text = (count - 1).ToString();
                    litTotalPrice.Text = (double.Parse(litTotalPrice.Text.Trim('￥')) - currentPrice).ToString("c2");
                    litProductCount.Text = (int.Parse(litProductCount.Text) - 1).ToString() ;
                }
                SetCookie();
            }
            else if (e.CommandName == "Increase")
            {
                double currentPrice = double.Parse(e.CommandArgument.ToString());
                TextBox txtBuyCount = e.Item.FindControl("txtBuyCount") as TextBox;
                int count = int.Parse(txtBuyCount.Text);
                if (count < 99)
                {
                    txtBuyCount.Text = (count + 1).ToString();
                    litTotalPrice.Text = (double.Parse(litTotalPrice.Text.Trim('￥')) + currentPrice).ToString("c2");
                    litProductCount.Text = (int.Parse(litProductCount.Text) + 1).ToString();
                }
                SetCookie();
            }
        }

        private string SetCookie()
        {
            string shoppingCart = "";
            foreach (RepeaterItem item in rpt.Items)
            {
                if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
                {
                    Literal litID = item.FindControl("litID") as Literal;
                    Literal litSize = item.FindControl("litSize") as Literal;
                    TextBox txtBuyCount = item.FindControl("txtBuyCount") as TextBox;
                    int tmp;
                    bool flag = int.TryParse(txtBuyCount.Text, out tmp);
                    if (flag == false)
                    {                        
                        return null;
                    }
                    shoppingCart += litID.Text + "_" + txtBuyCount.Text + "_" + Server.UrlEncode(litSize.Text) + ",";


                }
            }
            shoppingCart = shoppingCart.TrimEnd(',');
            HttpCookie cookie = new HttpCookie("ShoppingCart", shoppingCart);
            cookie.Expires = DateTime.Now.AddHours(12);
            Response.Cookies.Add(cookie);
            return shoppingCart;
        }

        protected void lnkNext_Click(object sender, EventArgs e)
        {

            string shoppingCart = SetCookie();

            if (shoppingCart == null)
            {
                JSUtil.Alert("数据格式不正确");
                return;
            }

            if (shoppingCart == "")
            {
                JSUtil.Alert("购物车里没有商品");
            }
            else
            {
                Response.Redirect("shopping2.aspx");
            }
        }

        protected void btnClear_Click(object sender, EventArgs e)
        {
            string shoppingCart = "";

            HttpCookie cookie = new HttpCookie("ShoppingCart", shoppingCart);
            cookie.Expires = DateTime.Now.AddHours(-1);
            Response.Cookies.Add(cookie);

            Response.Redirect("shopping1.aspx");
        }
    }
}